
//Program to create Paintbrush using java awt and swing in applet.


import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.JScrollBar.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import loader.uiThread;

import java.awt.geom.AffineTransform;
import java.awt.image.*;
            
public class paintingApplication extends JFrame implements ActionListener,AdjustmentListener,MouseListener,MouseMotionListener
{
 //Declaring constants to be used in  switch case later.
 
 public final int MAX_X          = 800;
 public final int MAX_Y          = 600;
 public final int NO_OP          = 0;
 public final int PEN_OP         = 1;
 public final int LINE_OP        = 2;
 public final int ERASER_OP      = 3;
 public final int CLEAR_OP       = 4;
 public final int RECT_OP        = 5;
 public final int OVAL_OP        = 6;
 public final int FRECT_OP       = 7;
 public final int FOVAL_OP       = 8;
 public final int POLY_OP        = 10;
 public final int Crop_OP        =11;
 public final int Paint_OP       =12;
 public int v,h,r;
//constants used to set Graphics Default.

 public int mousex                = 0;
 public  int mousey               = 0;
 public  int prevx                = 0;
 public int prevy                 = 0;
 
//Boolean values to set Status of Buttons.

 public boolean initialPen        = true;
 public boolean initialLine       = true;
 public boolean initialEraser     = true;
 public boolean initialRect       = true;
 public boolean initialOval       = true;
 public boolean initialFRect      = true;
 public boolean initialFOval      = true;
 public boolean initialPolygon    = true;
 public boolean initialSpline     = true;
 public boolean initialCrop       = true;
 public boolean initialPaint      = true;

//Declaring Constants to be used to Draw Rectangles and oval's Croping Images,Erasing etc.

 public int  Orx                  = 0;
 public int  Ory                  = 0;
 public int  OrWidth              = 0;
 public int  OrHeight             = 0;
 public int  drawX                = 0;
 public  int  drawY               = 0;
 public int  eraserLength         = 5;
 public int  udefRedValue         = 255;
 public int  udefGreenValue       = 255;
 public  int  udefBlueValue       = 255;
 
 //Setting Initial Status in Status panel. 
 
 public int    opStatus           = PEN_OP;
 public  int    colorStatus        = 1;

 //Defining color objects to be used with RGB values.
 
 Color  mainColor          = new Color(0,0,0);
 public Color  xorColor   = new Color(255,255,255);
 Color  statusBarColor     = new Color(255,255,255);
 Color  userDefinedColor   = new Color(udefRedValue,udefGreenValue,udefBlueValue);
 
 //Defining Buttons
 
 public JRadioButton penButton          = new JRadioButton("Pen");
 public JRadioButton lineButton         = new JRadioButton("Line");


 public JRadioButton rectButton         = new JRadioButton("Rectangle");
 public JRadioButton ovalButton         = new JRadioButton("Oval");
 public JRadioButton fillRectButton    = new JRadioButton("Filled Rectangle");
 public JRadioButton fillOvalButton    = new JRadioButton("Filled Oval");
 public JRadioButton brushButton      = new JRadioButton("Brush");
 public JRadioButton eraserButton       = new JRadioButton("Eraser");

 public JButton clearButton        = new JButton("Clear");
 
 public JButton polygonButton      = new JButton("");
 public JButton blackButton        = new JButton("");
 public JButton blueButton         = new JButton("");
 public JButton redButton          = new JButton("");
 public JButton greenButton        = new JButton("");
 public JButton purpleButton       = new JButton("");
 public JButton orangeButton       = new JButton("");
 public JButton pinkButton         = new JButton("");
 public JButton grayButton         = new JButton("");
 public JButton yellowButton       = new JButton("");
 public JButton userDefButton      = new JButton("");

 // Declaring JScrollBars which will be used to adjust colors.
   
 public JScrollBar redSlider       = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);

 public JScrollBar blueSlider      = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);

 public JScrollBar greenSlider     = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);
 
 //Textfields to be used.

 public JTextField colorStatusBar  = new JTextField(20);
 public  JTextField opStatusBar    = new JTextField(20);
 public JTextField mouseStatusBar  = new JTextField(10);
 public JTextField redValue        = new JTextField(3);
 public  JTextField greenValue     = new JTextField(3);
 public JTextField blueValue       = new JTextField(3);
 public	JTextField t,s;
 //labels
 
 JLabel blank1=new JLabel(" ");//used to adjust panel
 JLabel blank2=new JLabel(" ");
 JLabel blank3=new JLabel(" ");
 JLabel palet=new JLabel("Color Palet",JLabel.LEFT);

 public JLabel operationLabel      = new JLabel("   Tool mode:");
 public JLabel colorLabel          = new JLabel("   Color mode:");
 public JLabel cursorLabel         = new JLabel("   Cursor:");

//Panels and canvas to be used in program.


 public JPanel controlPanel        = new JPanel(new GridLayout(4,2,0,0));
 public JPanel controlPanel2 = new JPanel(new GridLayout(3,1,0,0));
 public JPanel controlPanel3 = new JPanel();

 public JPanel statusPanel         = new JPanel();
 public JPanel udefcolPanel        = new JPanel(new GridLayout(6,2,0,0));
 public JPanel udefdemcolPanel     = new JPanel();
 public JPanel colorPanel= new JPanel(new GridLayout(2,5,0,0)); 
 public JPanel westPanel=new JPanel(new GridLayout(2,2,0,0));
 public JPanel southPanel=new JPanel(new GridLayout(1,2,0,0));
 
 
 public  Canvas my= new Canvas();
 
//Image objects to manipulate images
 Image image,image1; 

//Defining main frame class.

class menuframe extends JFrame
{
        String msg= " ";
        menuframe(String title)    //class constructor the title passed to it will be displayed as heading of frame.
        {
        super(title);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        JMenuBar mbar=new JMenuBar();
        setJMenuBar(mbar);
        
        JMenu file=new JMenu("File"); //File Menu.
        JMenuItem item1;
        file.add(item1=new JMenuItem("New"));
        JMenu open=new JMenu("Open");
        JMenuItem item2,item8,item9,item10;
        open.add(item2=new JMenuItem("Car"));
        open.add(item8=new JMenuItem("Flower"));
        open.add(item9=new JMenuItem("Bouquet"));
         open.add(item10=new JMenuItem("Rainbow"));
        file.add(open);
        mbar.add(file);       //Adding to Menu Bar.

        JMenu im=new JMenu("image");    //Image Menu.
        JMenuItem item7,item11,item12;
        im.add(item7=new JMenuItem("AlterSize"));
        im.add(item11=new JMenuItem("Rotate"));
        im.add(item12=new JMenuItem("Crop"));
        mbar.add(im);        //Adding it to Menu Bar.
        
        Mymenuhandler han=new Mymenuhandler();
        
        //add Action to the items of menu.
        
        item1.addActionListener(han);
        item2.addActionListener(han);
        item8.addActionListener(han);
        item9.addActionListener(han);
        item10.addActionListener(han);
        item11.addActionListener(han);
        item12.addActionListener(han);
        item7.addActionListener(new AlterSize());
        
        MyWindowAdapter adapter=new MyWindowAdapter(this);//Used To Close Frame defined  in later part.
        addWindowListener(adapter);
       }
      
 }
 class MyWindowAdapter extends WindowAdapter    //Used to Close Menu Frame.
  {
        menuframe m;
        public MyWindowAdapter(menuframe m) 
        {
          this.m=m;
        }
        public void windowClosing(WindowEvent we) 
        {
          m.setVisible(false) ;
        }
  }  
 
//Dialog Box definition which will be used to Resize Images.

 class SampleDialog extends Dialog implements ActionListener
  {       
	
        SampleDialog(Frame parent,String title)
        {
                super(parent,title,false);
                setLayout(new GridLayout(2,2));
                setSize(300,200);
                JPanel p1=new JPanel();
                p1.add(new JLabel("        Horizontal    "));
                p1.add(new JLabel("        Vertical"));
                JPanel p2=new JPanel();
                p2.add(t=new JTextField(10));
                p2.add(s=new JTextField(10));
                JPanel p3=new JPanel();
                JButton d;
                p3.add(d=new JButton("ok"));
                d.addActionListener(this);
                add(p1);
                add(p2);
                add(p3);
                newadapter ada=new newadapter(this);
                addWindowListener(ada);     //Used to close Dialog Box.
                
          }
          public void actionPerformed(ActionEvent ae)
          {
                 h=Integer.parseInt(s.getText());
                 v=Integer.parseInt(t.getText());
                 Graphics g=my.getGraphics();
                 g.setColor(Color.white);
                 g.fillRect(0,0,my.getBounds().width,my.getBounds().height); 
                 dispose();
                 newpaint(my);
           }
          
 }
 
 class newadapter extends WindowAdapter     //Code for Close Button of Alter Size Dialog.
 {
	SampleDialog d;
	   public newadapter(SampleDialog d) 
        {
        this.d=d;
        }
	   public void windowClosing(WindowEvent ae)
	    {
		    d.setVisible(false);
	    }
 }
 
 //Dialog Box to Rotate Image.
 
 class imagerot extends Dialog implements ActionListener
 {
 	JTextField k;
 	imagerot(Frame parent,String Title)
 	{
 		super(parent,Title,false);
 		setLayout(new FlowLayout());
 		setSize(200,200);
 		JLabel l;
        JButton b;
 		add(l=new JLabel("Enter the Angle"));
 		add(k=new JTextField(10));
 		add(b=new JButton("Ok"));
 		b.addActionListener(this);
 		rotAdapter rd=new rotAdapter(this);
 		
 		addWindowListener(rd);
 	}
 	public void actionPerformed(ActionEvent ae)
 	{
 		r=Integer.parseInt(k.getText());
 		dispose();
 	    clearcanvas(my);
 		spaint(my);
 	}
 }

class rotAdapter extends WindowAdapter  //Code For Close Button of Image Rotate Dialog Box.
{
	imagerot rt;
	rotAdapter(imagerot rt)
	{
		this.rt=rt;
	}
	public void windowClosing(WindowEvent e)
	{
		rt.setVisible(false);
	}
}

//Code to perform Action after Clicking MenuItem.
public class Mymenuhandler implements ActionListener
{
    menuframe me;
	public void actionPerformed(ActionEvent ae)
	{
	   String arg=(String)ae.getActionCommand();
	   	if(arg.equals("New"))
	   	{
	   		clearcanvas(my);
	   	}
	   	else if(arg.equals("Car"))
	   	{
	   		 ImageIcon icon=new ImageIcon("Car2.JPG");
	   		 image=icon.getImage();
	   		 clearcanvas(my);
             ipaint(my);
               
	   	}
	   	else if(arg.equals("Flower"))
	   	{
	   	    ImageIcon icon=new ImageIcon("flower4.JPG");
	   	    image=icon.getImage();
	   	    clearcanvas(my);
	   		ipaint(my);
	   		
	   	}
	   	else if(arg.equals("Bouquet"))
	   	{
	   		ImageIcon icon=new ImageIcon("Bouquet.JPG");
	   		image=icon.getImage();
	   		clearcanvas(my);
	   		ipaint(my);
	   	}
	   	else if(arg.equals("Rainbow"))
	   	{
	   		ImageIcon icon=new ImageIcon("Rainbow.JPG");
	   		image=icon.getImage();
	   		clearcanvas(my);
	   		ipaint(my);
	   	}
	   	else if(arg.equals("Rotate"))
	   	{
	   		
	   		imagerot i=new imagerot(me,"Image Rotator");
	   	    
	   		i.setVisible(true);
	   	}
	   	else if(arg.equals("Crop"))
	   	{
	   	 opStatus=Crop_OP;
	   	 opStatusBar.setText("Croping");
	   	}
	}
}

//code to display Alter Image Dialog Box.
public class AlterSize implements ActionListener
{
	menuframe me;
	public void actionPerformed(ActionEvent e)
	{
	   
	   SampleDialog d=new SampleDialog(me,"Alter Image Size");
	   
	   
	   d.setVisible(true);
	}
}

//Initial Components To be Shown on Frame when Program get Executed.

public void init()
{
  //Initializing Main Frame with Specified size.
  
  JFrame f=new menuframe("Java Painting Application");
  int w=800;
  int h=600;
  setSize(new Dimension(w,h));
  f.setSize(1000,600);
   //objects in Color Palet
 
   colorPanel.add(palet); 
   colorPanel.add(blackButton);
   colorPanel.add(blueButton);
   colorPanel.add(redButton);
   colorPanel.add(greenButton);
   colorPanel.add(purpleButton);
   colorPanel.add(blank2);
       
    colorPanel.add(orangeButton);

    colorPanel.add(pinkButton);

    colorPanel.add(grayButton);
 
    colorPanel.add(yellowButton);
 
    colorPanel.add(userDefButton);

 //Setting Background of color Buttons.
    blackButton.setBackground(Color.black);
    blueButton.setBackground(Color.blue);
    redButton.setBackground(Color.red);
    greenButton.setBackground(Color.green);
    purpleButton.setBackground(Color.magenta);
    orangeButton.setBackground(Color.orange);
    pinkButton.setBackground(Color.pink);
    grayButton.setBackground(Color.gray);
	yellowButton.setBackground(Color.yellow);
    userDefButton.setBackground(userDefinedColor);
   	
 //Panel Containing Tool Buttons of Paint.
    controlPanel.add(penButton);
    controlPanel.add(lineButton);
    controlPanel.add(rectButton);
    controlPanel.add(ovalButton);
    controlPanel.add(fillRectButton);
    controlPanel.add(fillOvalButton);
    controlPanel.add(brushButton);
    controlPanel.add(eraserButton);
    
    ButtonGroup group = new ButtonGroup();
    group.add(penButton);
    group.add(lineButton);
    group.add(rectButton);
    group.add(ovalButton);
    group.add(fillRectButton);
    group.add(fillOvalButton);
    group.add(brushButton);
    group.add(eraserButton);
    
    //controlPanel.add(polygonButton);

    controlPanel.setBounds(0,0,100,300);
    TitledBorder leftBorder = BorderFactory.createTitledBorder("Paint Tools");
    leftBorder.setTitleJustification(TitledBorder.LEFT);
    
    
    controlPanel3.add(clearButton);
 
    controlPanel2.add(controlPanel3);
    controlPanel2.add(udefcolPanel);
    
 	controlPanel2.add(udefdemcolPanel);
 
 //code For UserDefined Color Panel Appearance.
 	JLabel redVal = new JLabel("Red Color");
 	JLabel blueVal = new JLabel("Blue Color");
 	JLabel greenVal = new JLabel("Green Color");
 	udefcolPanel.add(redVal);
 	
    udefcolPanel.add(redSlider);
    udefcolPanel.add(greenVal);
    udefcolPanel.add(greenSlider);
    udefcolPanel.add(blueVal);
    udefcolPanel.add(blueSlider);
  
  //Status Panel appearing At the top After Execution.
  	statusPanel.add(colorLabel);
 	statusPanel.add(colorStatusBar);
	statusPanel.add(operationLabel);
	statusPanel.add(opStatusBar);
  	statusPanel.add(cursorLabel);
	statusPanel.add(mouseStatusBar);
   	colorStatusBar.setEditable(false);//After This we cannot change Value of Text box
 	opStatusBar.setEditable(false);
 	mouseStatusBar.setEditable(false);
	statusPanel.setBackground(statusBarColor);

 
 //Adding all Panels To Main Frame.  
   
   //westPanel.setBackground(Color.gray);
   westPanel.setBorder(leftBorder);
   //southPanel.add(colorPanel); 
   //southPanel.add(blank3);  
   southPanel.add(statusPanel);
   southPanel.setBackground(Color.white);
   
   f.add(southPanel,"South");

   westPanel.add(controlPanel);
   westPanel.add(controlPanel2);

   f.add(westPanel, "West");
   f.setVisible(true);
   f.add(my, "Center");

    
 // Setup action listener 
    
	penButton.addActionListener(this);
    lineButton.addActionListener(this);
	eraserButton.addActionListener(this);
	clearButton.addActionListener(this);
  	rectButton.addActionListener(this);
	ovalButton.addActionListener(this);
   	fillRectButton.addActionListener(this);
  	fillOvalButton.addActionListener(this);
 	brushButton.addActionListener(this);
	polygonButton.addActionListener(this);
	
	blackButton.addActionListener(this);
  	blueButton.addActionListener(this);
    redButton.addActionListener(this);
    greenButton.addActionListener(this);
	purpleButton.addActionListener(this);
	orangeButton.addActionListener(this);
	pinkButton.addActionListener(this);
	grayButton.addActionListener(this);
  	yellowButton.addActionListener(this);
	userDefButton.addActionListener(this);
	
	redSlider.addAdjustmentListener(this);//Used For Adjusting Colors.
 	blueSlider.addAdjustmentListener(this);
  	greenSlider.addAdjustmentListener(this);

    my.addMouseMotionListener(this);
    my.addMouseListener(this);

    this.addMouseListener(this);
    this.addMouseMotionListener(this);

	updateRGBValues();//Fuction Defined Later In Program.
	
	//Initial values In Status Panel
	
	opStatusBar.setText("Pen");
 	colorStatusBar.setText("Black");
 	
}

//Setting Operation Status That is Which Tool is selected.

public void actionPerformed(ActionEvent e)

 {
 
    if (e.getActionCommand() == "Pen")

       opStatus = PEN_OP;


    if (e.getActionCommand() == "Line")

       opStatus = LINE_OP;

  
    if (e.getActionCommand() == "Eraser")

       opStatus = ERASER_OP;

  
    if (e.getActionCommand() == "Clear")
    
       opStatus = CLEAR_OP;

    
	if (e.getActionCommand() == "Rectangle")
   
      opStatus = RECT_OP;

 
   if (e.getActionCommand() == "Oval")
     
  	  opStatus = OVAL_OP;

 
   if (e.getActionCommand() == "Filled Rectangle")

       opStatus = FRECT_OP;

   
   if (e.getActionCommand() == "Filled Oval")

       opStatus = FOVAL_OP;

 
   if (e.getActionCommand() == "Polygon")

       opStatus = POLY_OP;

  
   if (e.getActionCommand() == "Brush")
 
      opStatus =Paint_OP;


   if (e.getSource() == blackButton)

       colorStatus = 1;

  
   if (e.getSource() == blueButton)
   
       colorStatus = 2;

   if (e.getSource() == greenButton)
 
       colorStatus = 3;

   
   if (e.getSource() == redButton)
   
       colorStatus = 4;


   if (e.getSource() == purpleButton)
    
       colorStatus = 5;

  
   if (e.getSource() == orangeButton)
    
   	   colorStatus = 6;

   if (e.getSource() == pinkButton)
 
      colorStatus = 7;


   if (e.getSource() == grayButton)
 
      colorStatus = 8;


   if (e.getSource() == yellowButton)
  
      colorStatus = 9;

  if (e.getSource() == userDefButton)
  
     colorStatus = 10;

    initialPolygon = true;

    initialSpline   = true;

  //Setting Values In TextField According to Selected Operation.
  
  switch (opStatus)
   {
     
    case PEN_OP   : 
		opStatusBar.setText("Pen");
 		break;
 
    case LINE_OP  : 
		opStatusBar.setText("Line");
  		break;

	case ERASER_OP: 
		opStatusBar.setText("Eraser");
		break;

	case CLEAR_OP : 
		clearcanvas(my);
		break;

	case RECT_OP  : 
		opStatusBar.setText("Rectangle");
		break;
		
	case OVAL_OP  :
	 	opStatusBar.setText("Oval");
 		break;
	
	case FRECT_OP : 
		opStatusBar.setText("Fill-Rectangle");
 		break;
	
	case FOVAL_OP : 
		opStatusBar.setText("Fill-Oval");
		break;

	case POLY_OP : 
		opStatusBar.setText("Polygon");
    	break;

	case Paint_OP: 
		opStatusBar.setText("Brush");
      	break;
}


 
   /* Update Color status bar, with current color */
 
   switch (colorStatus)
    {


       case  1:
	 		colorStatusBar.setText("Black");
			break;

	   case  2:  
       		colorStatusBar.setText("Blue");
			break;

	   case  3:
	   	  colorStatusBar.setText("Green");
	   	  break;

	   case  4:  
	   	  colorStatusBar.setText("Red");
	   	  break;

	   case  5:  
	   	   colorStatusBar.setText("Purple");
 		   break;
		
	   case  6: 
	   	   colorStatusBar.setText("Orange");
		   break;

       case  7: 
       	   colorStatusBar.setText("Pink");
  		   break;
  		  
  	   case  8: 
  	   	   colorStatusBar.setText("Gray");
		   break;
		  
	   case  9:
	   	   colorStatusBar.setText("Yellow");
		   break;

	   case 10:
	   	   colorStatusBar.setText("User Defined Color");
		   break;

   }
    //Both Function Are Declared in Later part of the Program Used To set main color and RGB values
    
    setMainColor();
   updateRGBValues();
}

//called When Color Slider is moved
public void adjustmentValueChanged(AdjustmentEvent e)
{
	//Adjusting Negative values to Zero And Maximum upto 255 After Moving Slider
    updateRGBValues();
    setMainColor();
}

//Used to Set Applet NOTE:This doesn't deal with Frame at all.
public void paint(Graphics g)
{
	super.paint(g);
	g.drawImage(image1,drawX,drawY,OrWidth,OrHeight,this);
}

//Drawing Image On Canvas
public void ipaint(Canvas p)
 {
 	Graphics g=p.getGraphics();
    g.drawImage(image,55,0,p);
 }
 
//To Redraw image after Altering it.

public void newpaint(Canvas p)
 {
 	Graphics g=p.getGraphics();
 	g.drawImage(image,55,0,v,h,p);
 }
 
//Draws Rectangle of white color of the size of canvas.user seems that canvas is cleared.
public void clearcanvas(Canvas p)
 {

	    opStatusBar.setText("Clear");

	    Graphics g = p.getGraphics();

   	     g.setColor(Color.white);
       
	   g.fillRect(0,0,p.getBounds().width,p.getBounds().height);
  }

//Used To Draw Image After Rotating it.

public void spaint(Canvas p)
  {
  	Graphics g=p.getGraphics();
  	Graphics2D g2d = (Graphics2D) g;
  	AffineTransform tx = new AffineTransform();//predefined Class Which is Imported At the Begining of program.

    double x = 50;
    double y = 150;
    tx.translate(x, y);//predefined method to translate image.
    
    double radians = -r*(Math.PI/180);//Converting given angle r into Radians.
    
    tx.rotate(radians);//rotates the specfied Image.
    g2d.drawImage(image,tx,this);
  }

//Defining all paint tools in program.

public void penOperation(MouseEvent e)
 {
    Graphics g  = my.getGraphics();
 
   g.setColor(mainColor);
   if(initialPen)
   {
   	setGraphicalDefaults(e);//Initializing values of mouse coordinates.
    initialPen = false;
    g.drawLine(prevx,prevy,mousex,mousey);
   }
 
   if (mouseHasMoved(e))//Action after moving mouse.
   {
     
	  mousex = e.getX();
	  mousey = e.getY();
      g.drawLine(prevx,prevy,mousex,mousey);
 
      prevx = mousex;//setting new coordinates as previous

      prevy = mousey;

    }
 }
 
public void lineOperation(MouseEvent e)

 {

   
 Graphics g  = my.getGraphics();
 
   g.setColor(mainColor);
   
 if (initialLine)
  
  {
       setGraphicalDefaults(e);

       g.setXORMode(xorColor);//Used to get Fine Line Removing all Unwanted pixels
   
       g.drawLine(Orx,Ory,mousex,mousey);//draws point when mouse just clicked.
  
       initialLine=false;
   }

  if (mouseHasMoved(e))

   {
       g.setXORMode(xorColor);

       g.drawLine(Orx,Ory,mousex,mousey);
      
      //setting new Coordinates.
       mousex = e.getX();
 
       mousey = e.getY();
      
       g.drawLine(Orx,Ory,mousex,mousey);//draws Line till it is not realeased.
    }
 }
 public void rectOperation(MouseEvent e)
 {
    
	Graphics g  = my.getGraphics();

   	g.setColor(mainColor);//Sets Color Of Rectangle.

     if (initialRect)
     {
       setGraphicalDefaults(e);

       initialRect = false;
     }
     if (mouseHasMoved(e))
 
     {
       g.setXORMode(my.getBackground());//Used To draw smooth Rectangle.

       g.drawRect(drawX,drawY,OrWidth,OrHeight);
      
       mousex = e.getX();
 
       mousey = e.getY();

       setActualBoundry();//Function Defined later To set Values of some coordinates.

       g.drawRect(drawX,drawY,OrWidth,OrHeight);//draws Rectangle till it is not released.
     }

 }

//Function to Crop Image
public void imageCroping(MouseEvent e)
{
	Graphics g=my.getGraphics();
	if(initialCrop)
	{
	setGraphicalDefaults(e);//Initializing values of mouse coordinates
	initialCrop=false;
	}
	if(mouseHasMoved(e))
	{
		g.setXORMode(my.getBackground());

		g.drawRect(drawX,drawY,OrWidth,OrHeight);
		mousex=e.getX();
		mousey=e.getY();
		setActualBoundry();
		g.drawRect(drawX,drawY,OrWidth,OrHeight);
	}
}

//Draws Oval shape code is simillar to Drawing Rectangle 
public void ovalOperation(MouseEvent e)

 {
 
   	Graphics g  = my.getGraphics();
 
 	g.setColor(mainColor);
    if (initialOval)
    {
       setGraphicalDefaults(e);//Initializing values of mouse coordinates
 
       initialOval=false;
    }
    if (mouseHasMoved(e))
  
    {
      g.setXORMode(xorColor);
   
      g.drawOval(drawX,drawY,OrWidth,OrHeight);

      mousex = e.getX();
  
      mousey = e.getY();

      setActualBoundry();
  
      g.drawOval(drawX,drawY,OrWidth,OrHeight);
    
     }

  }

//Draws Filled Rectangle.
 public void frectOperation(MouseEvent e)

 {
  
  Graphics g  = my.getGraphics();
  
  g.setColor(mainColor);

    if (initialFRect)
  
     {
       setGraphicalDefaults(e);//Initializing values of mouse coordinates
  
       initialFRect=false;

     }
    if (mouseHasMoved(e))
   
     {
       g.setXORMode(xorColor);
    
       g.drawRect(drawX,drawY,OrWidth,OrHeight);
    
       mousex = e.getX();

       mousey = e.getY();

       setActualBoundry();
  
       g.drawRect(drawX,drawY,OrWidth,OrHeight);
     }

  }

//Draws Filled Oval

public void fovalOperation(MouseEvent e)
 
{
    Graphics g  = my.getGraphics();

    g.setColor(mainColor);

    if (initialFOval)
   
 	{
       setGraphicalDefaults(e);//Initializing values of mouse coordinates
  
       initialFOval = false;
   
    }

    if (mouseHasMoved(e))
    {
 
      g.setXORMode(xorColor);

      g.drawOval(drawX,drawY,OrWidth,OrHeight);

      mousex = e.getX();
  
      mousey = e.getY();

      setActualBoundry();
   
      g.drawOval(drawX,drawY,OrWidth,OrHeight);
   
    }

}

//Erases The Content of canvas.
 
public void eraserOperation(MouseEvent e)
{

  Graphics g  = my.getGraphics();
  if (initialEraser)
  {
    setGraphicalDefaults(e);

	initialEraser = false;

    g.setColor(Color.white);
 
    
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
   
    g.setColor(Color.black);
    //Draws Rectangle of Side 10 when mouse is Clicked.around mouse pointer. 
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
   
    prevx = mousex;
 
    prevy = mousey;
   }

    if (mouseHasMoved(e))
    {
       g.setColor(mainColor.white);
       //draws white color Rectangle whenever clicked
       g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);

       mousex  = e.getX();
       mousey  = e.getY();
  
       g.setColor(mainColor.white);
       //draws filled rectangle when dragged. 
       g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
       g.setColor(Color.black);
       g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
 
       prevx = mousex;
       prevy = mousey;
     }
}

//Performs Brushing on canvas

public void brushOperation(MouseEvent e)
{

  Graphics g  = my.getGraphics();
  if (initialPaint)
  {
    setGraphicalDefaults(e);

	initialPaint = false;

    g.setColor(mainColor);
 
    
    g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
   
    g.setColor(Color.black);
    //Draws Rectangle of Side 10 when mouse is Clicked.around mouse pointer. 
    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
   
    prevx = mousex;
 
    prevy = mousey;
   }

    if (mouseHasMoved(e))
    {
       g.setColor(mainColor);
       //draws selected color Rectangle whenever clicked
       g.drawRect(prevx-eraserLength, prevy-eraserLength,eraserLength*2,eraserLength*2);

       mousex  = e.getX();
       mousey  = e.getY();
  
       g.setColor(mainColor);
       //draws filled rectangle when dragged. 
       g.fillRect(mousex-eraserLength, mousey-eraserLength,eraserLength*2,eraserLength*2);
       g.setColor(Color.black);
       g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
 
       prevx = mousex;
       prevy = mousey;
     }
}


//Draws Polygon
 public void polygonOperation(MouseEvent e)
 
{
    
	if (initialPolygon)
   
	 {

       	prevx = e.getX();

	       prevy = e.getY();

       initialPolygon = false;
  
  }


 
   	else
   
	 {
   
		    mousex = e.getX();

		    mousey = e.getY();

		    Graphics g = my.getGraphics();
   
		    g.setColor(mainColor);

	 	    g.drawLine(prevx,prevy,mousex,mousey);
   
		    prevx = mousex;
 
	      	prevy = mousey;
       }

}


//return true if mouse moves
public boolean mouseHasMoved(MouseEvent e)
    {
   
	 return (mousex != e.getX() || mousey != e.getY());

	 }

//Finds The top-left coordinate of rectangle with Height and width.
public void setActualBoundry()
    {
 
      if (mousex < Orx || mousey < Ory)
      {
      
   	     if (mousex < Orx)
   
	     {
            OrWidth = Orx - mousex;
            drawX   = Orx - OrWidth;
   
     	 }
		 else
    	 {
  
           drawX    = Orx;
    
           OrWidth  = mousex - Orx;
		  }

         if (mousey < Ory)
     
 	     {
    
      	   OrHeight = Ory - mousey;
 
	       drawY    = Ory - OrHeight;
         }
       
         else
          
		 {
         
	    	drawY    = Ory;
  
	        OrHeight = mousey - Ory;
  
 	     }
      }
 
     else
  		
  		{
	
	         drawX    = Orx;

             drawY= Ory;
 
	         OrWidth  = mousex - Orx;
 
         	 OrHeight = mousey - Ory;
  		}

	} 

//Setting Initial mouse Coordinates.

public void setGraphicalDefaults(MouseEvent e)
      {
   
		 mousex   = e.getX();
 
		 mousey   = e.getY();
 
		 prevx    = e.getX();

		 prevy    = e.getY();

		 Orx      = e.getX();
 
		 Ory      = e.getY();
  
		 drawX    = e.getX();
  
		 drawY    = e.getY();
   
		 OrWidth  = 0;
 	
		 OrHeight = 0;
	  }

//This method is called when Mouse is moved.
 public void mouseDragged(MouseEvent e)
      {
 
		   updateMouseCoordinates(e);
           //calling methods of respective tools
           switch (opStatus)
 
		   {
   
		    case PEN_OP   : 
				penOperation(e);
                break;

   			case LINE_OP  : 
				lineOperation(e);
                break;

			case RECT_OP  : 
				rectOperation(e);
				break;

			case OVAL_OP  : 
				ovalOperation(e);
      		    break;

  	 	    case FRECT_OP : 
  	 	    	frectOperation(e);
  	 	    	break;
    
		    case FOVAL_OP : 
		    	fovalOperation(e);
				break;
  
		    case ERASER_OP: 
		    	eraserOperation(e);
				break;
             
            case Crop_OP:
             	imageCroping(e);
                break;
                
            case Paint_OP:
            	brushOperation(e);
            	break;
		   }

    }

 //This method Is called When mousereleased event is generated.
 public void mouseReleased(MouseEvent e)
   {
         updateMouseCoordinates(e);
         
         //methods are called according to selected Tools.
         
         switch (opStatus)
         {
   			case PEN_OP    :
			      releasedPen();
                  break;
			
			case LINE_OP   : 
				releasedLine();
                break;
			
			case RECT_OP   : 
				releasedRect();
                break;
  			
  			case OVAL_OP   : 
  				releasedOval();
				break;

			case FRECT_OP  : 
				releasedFRect();
				break;
   
		    case FOVAL_OP  :
			 	releasedFOval();
                break;
  
		    case ERASER_OP :
 				releasedEraser();
 				break;
		      
		    case Crop_OP:
		      	releasedCrop();
		      	break;
		     
		    case Paint_OP:
		    	releasedBrush();
		    	break;
   
		   }

  }

public void mouseEntered(MouseEvent e)

	 {
   
		 updateMouseCoordinates(e);
	 }
 
//setup color in color status.
public void setMainColor()
	{
	mainColor = new Color(redSlider.getValue(),greenSlider.getValue(),blueSlider.getValue());
    }

//All Operation performed When Mouse Is Realeased.
public void releasedPen()
{
  initialPen = true;
}

public void releasedLine()
 {
 
		   if ((Math.abs(Orx-mousex)+Math.abs(Ory-mousey)) != 0)
    
			{
  
			     initialLine = true;

	       		Graphics g  = my.getGraphics();

			       g.setColor(mainColor);
  
			     g.drawLine(Orx,Ory,mousex,mousey);

		    }


	 }
 
	public void releasedEraser()

		 {

 
		   initialEraser = true;

		   Graphics g  = my.getGraphics();
   
		   g.setColor(mainColor.white);

		   g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);

         }
	 
    public void releasedBrush()
         {
            initialEraser = true;

		    Graphics g  = my.getGraphics();
   
			g.setColor(mainColor);

		    g.drawRect(mousex-eraserLength,mousey-eraserLength,eraserLength*2,eraserLength*2);
   
         }
 public void releasedRect()
 
	{

    
		   initialRect = true;

		   Graphics g  = my.getGraphics();

	 	   g.setColor(mainColor);

	 	   g.drawRect(drawX,drawY,OrWidth,OrHeight);

 
	}
  public void releasedCrop()
  {
  	initialCrop=true;
  	Graphics g=my.getGraphics();
  	g.drawRect(drawX,drawY,OrWidth,OrHeight);
  	
    //Draws Croped Area On Applet
  	image1=createImage(new FilteredImageSource(image.getSource(),new CropImageFilter(drawX,drawY,OrWidth,OrHeight)));
  	repaint();
  }
 public void releasedOval()
 
	{
		initialOval = true;

	    Graphics g  = my.getGraphics();

	    g.setColor(mainColor);
  
	    g.drawOval(drawX,drawY,OrWidth,OrHeight);
	}

public void releasedFRect()
 	{
		initialFRect = true;

	    Graphics g  = my.getGraphics();
 
	   	g.setColor(mainColor);
  
	  	g.fillRect(drawX,drawY,OrWidth,OrHeight);
	}
 
public void releasedFOval()
 
	{
		 initialFOval = true;
   
	 	 Graphics g  = my.getGraphics();

	     g.setColor(mainColor);
  
  	  	 g.fillOval(drawX,drawY,OrWidth,OrHeight);
	}

//Set Ups Mouse coordinates on status panel. 
public void updateMouseCoordinates(MouseEvent e)
 {
    
	String xCoor ="";
 
	String yCoor ="";

    if (e.getX() < 0) 
		xCoor = "0";
    
    else
   		{

    		   xCoor = String.valueOf(e.getX());//converts value to string.

		}

 	if (e.getY() < 0)
		 xCoor = "0";

	else
   
	    {
       
			   yCoor = String.valueOf(e.getY());//converts value to string.

		}

 
		 mouseStatusBar.setText("x:"+xCoor+"   y:"+yCoor);


}

 public void updateRGBValues()
 {  
	udefRedValue = redSlider.getValue();

	udefGreenValue = greenSlider.getValue();

	udefBlueValue = blueSlider.getValue();

	    if (udefRedValue > 255)

	       udefRedValue = 255;

 
	    if (udefRedValue < 0 )

	       udefRedValue =0;

    	if (udefGreenValue > 255)
  
	       udefGreenValue = 255;


	    if (udefGreenValue < 0 )

	       udefGreenValue =0;

   
	    if (udefBlueValue > 255)
    
	       udefBlueValue = 255;

    
	    if (udefBlueValue < 0 )

	       udefBlueValue =0;

   
	 redValue.setText(String.valueOf(udefRedValue));
    
	 greenValue.setText(String.valueOf(udefGreenValue));

	 blueValue.setText(String.valueOf(udefBlueValue));

     userDefinedColor = new Color(udefRedValue,udefGreenValue,udefBlueValue);

	 userDefButton.setBackground(userDefinedColor);

	 Graphics g = udefdemcolPanel.getGraphics();

 	 g.setColor(userDefinedColor);

	 g.fillRect(0,0,800,800);

	 }

//Handles mouse clicked events.
public void mouseClicked(MouseEvent e)
{
	updateMouseCoordinates(e);

	 switch (opStatus)
  
		  {
	 		    case 10 : polygonOperation(e);

			                 break;
		  }
}
 
public void mouseExited(MouseEvent e)
 
	{
		updateMouseCoordinates(e);

	}

public void mouseMoved(MouseEvent e)
	{
    	updateMouseCoordinates(e);
	}
public void mousePressed(MouseEvent e)
 	{
		updateMouseCoordinates(e);
	}

public static void main(String args[])
{
    String[] ar = null;
	Thread mainThread = Thread.currentThread();
    uiThread myThread = new uiThread(ar, mainThread);
	myThread.run();
	
	paintingApplication application = new paintingApplication();
	application.init();
	
}
} 

